<?php
declare (strict_types = 1);

namespace app\command;

use app\frontend\model\Article;
use app\frontend\model\ArticleDoc;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Env;
use tools\es\MyElasticsearch;

class Es extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('es')
            ->addOption('createIndex', null, Option::VALUE_REQUIRED, '创建索引')
            ->addOption('addDoc', null, Option::VALUE_REQUIRED, '添加文档')
            ->addOption('updateIndex', null, Option::VALUE_REQUIRED, '更新文章索引')
            ->setDescription('es命令');
    }

    protected function execute(Input $input, Output $output)
    {
        $es = new MyElasticsearch();
        $index = Env::get('es.index', 'dev_article_dev');

        if ($input->hasOption('createIndex')) {
            // 创建索引
            $indexName = $input->getOption('createIndex');

            if ($es->existsIndex($indexName) != false) {
                $output->writeln('该索引已存在');
            } else {
                $es->createIndex($indexName);
                $output->writeln('索引添加成功');
            }
        } elseif ($input->hasOption('addDoc')) {
            // 添加文档
            // 取出所有文章
            $i = 0;
            $article = Article::with(['articleContent', 'articleCategory'])
                ->where('status', 2)
                ->limit($i, 10)
                ->select();
            if (!$article->isEmpty()) {
                foreach ($article as $v) {
                    $articleItem = [
                        'id' => $v['id'],
                        'title' => $v['title'],
                        'category' => empty($v['category']) ? '顶级分类' : $v['category'],
                        'content' => strip_tags(htmlspecialchars_decode($v['articleContent']['content'])),
                        'create_time' => $v['create_time']
                    ];
                    $es->addDoc($articleItem['id'], $articleItem, $index, '_doc');
                }
            }
            $output->writeln('添加文档成功');
        } elseif ($input->hasOption('updateIndex')) {
            // 更新文章索引
            $articleIndexList = ArticleDoc::limit(10)
                ->select();
            if ($articleIndexList->isEmpty()) {
                $output->writeln("成功");
            } else {
                foreach ($articleIndexList as $v) {
                    if ($v->status == 2) {
                        // 需要删除对应的es文档
                        // 先检查有没有对应的文档
                        $res = $es->existsDoc($v->article_id, $index, '_doc');
                        if ($res) {
                            $es->deleteDoc($v->article_id, $index, '_doc');
                        }
                    } else {
                        // 需要新增或重新生成es文档
                        // 获取文章数据
                        $article = Article::with(['articleContent', 'articleCategory'])
                            ->where('id', $v->article_id)
                            ->find();
                        if (!$article) {
                            // 如果获取不到文章数据，则删除该记录，然后跳转到下一条继续处理
                            ArticleDoc::destroy($v->id);
                            continue;
                        }
                        $article = $article->toArray();
                        // 先检查有没有对应的文档
                        $res = $es->existsDoc($v->article_id, $index, '_doc');
                        if ($res) {
                            // 如果对应的文档存在，则更新文档
                            $articleItem = [
                                'doc' => [
                                    'title' => $article['title'],
                                    'category' => empty($article['category']) ? '顶级分类' : $article['category'],
                                    'content' => strip_tags(htmlspecialchars_decode($article['articleContent']['content'])),
                                    'create_time' => $article['create_time']
                                ]
                            ];
                            $es->updateDoc($article['id'], $index, '_doc', $articleItem);
                        } else {
                            // 如果对应的文档不存在，则添加文档
                            $articleItem = [
                                'id' => $article['id'],
                                'title' => $article['title'],
                                'category' => empty($article['category']) ? '顶级分类' : $article['category'],
                                'content' => strip_tags(htmlspecialchars_decode($article['articleContent']['content'])),
                                'create_time' => $article['create_time']
                            ];
                            $es->addDoc($articleItem['id'], $articleItem, $index, '_doc');
                        }
                    }

                    // 删除article_index表对应的记录
                    ArticleDoc::destroy($v->id);
                }
                $output->writeln("成功");
            }
        } else {
            $output->writeln('选项错误');
        }

    }
}
